#define _CRT_SECURE_NO_WARNINGS

// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};
 
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* pcur1 = l1;
        ListNode* pcur2 = l2;
        ListNode* anshead = new ListNode(pcur1->val + pcur2->val);
        ListNode* pcur = anshead;
        while (pcur1 && pcur2) {
            ListNode* newnode = new ListNode(pcur1->val + pcur2->val);
            pcur->next = newnode;
            pcur = pcur->next;
            pcur1 = pcur1->next;
            pcur2 = pcur2->next;
        }
        if (pcur1 == nullptr) pcur->next = pcur2;
        else pcur->next = pcur1;
        pcur = anshead->next;
        while (pcur->next) {
            if (pcur->val > 9) {
                pcur->val -= 10;
                pcur->next->val += 1;
            }
            pcur = pcur->next;
        }
        if (pcur->val > 9) {
            ListNode* newnode = new ListNode(1);
            pcur->next = newnode;
            pcur->val -= 10;
        }
        return anshead->next;
    }
};

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* pcur = head;
        int count = 0;
        while (pcur) {
            count++;
            pcur = pcur->next;
        }
        int step = count - n - 1;
        pcur = head;
        if (step < 0) {
            if (!(head->next))
                return nullptr;
            head = head->next;
        }
        while (step-- > 0) {
            pcur = pcur->next;
        }
        if (pcur->next)
            pcur->next = pcur->next->next;
        return head;
    }
};

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head)return nullptr;
        if (!(head->next))return head;
        ListNode* prev = head;
        ListNode* pcur = head->next;
        ListNode* pnext = pcur->next;
        head = head->next;
        while (pnext && pnext->next) {
            prev->next = pnext->next;
            pcur->next = prev;
            pcur = prev->next;
            prev = pnext;
            pnext = pcur->next;
        }
        if (!pnext) {
            pcur->next = prev;
            prev->next = pnext;
        }
        else {
            pcur->next = prev;
            prev->next = pnext;
        }
        return head;
    }
};